
package com.aris.voicechecking;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.voicecheck.provider.DataProviderV2;
import com.voicecheck.v2.model.LessonModel;
import com.voicecheck.v2.model.SentencesModel;
import com.voicecheck.v2.model.UrlModel;

public class FlashScreenActivity extends Activity {

    protected SharedPreferences reference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flash_screen);

        reference = getSharedPreferences(getString(R.string.user_data), Context.MODE_PRIVATE);

        (new Handler()).postDelayed(new Runnable() {

            @Override
            public void run() {
                // genfile();
                Intent mainIntent = new Intent(FlashScreenActivity.this, MainActivity.class);

                startActivity(mainIntent);

                finish();

            }

        }, 2000);

        if (!reference.getBoolean(getString(R.string.user_data_about_blank), false)) {
            generateDataV2();

        }

    }

    // private void genImg() {
    //
    // try {
    //
    // String m_path = Environment.getExternalStoragePublicDirectory(
    // Environment.DIRECTORY_PICTURES).getAbsolutePath();
    //
    // for (int i = 1; i <= 8; i++) {
    // for (int j = 1; j <= 4; j++) {
    // for (int t = 1; t <= 6; t++) {
    //
    // InputStream is = getAssets().open("picture.png");
    // File fileoutput = new File(m_path, "W" + i + "D" + j + "L" + t + ".png");
    //
    // Log.d("gen file ----> ", fileoutput.getAbsolutePath());
    // OutputStream out = new FileOutputStream(fileoutput);
    // copyFile(is, out);
    // }
    //
    // }
    // }
    //
    // } catch (Exception e) {
    //
    // }
    //
    // }

    // private void genfile() {
    //
    // try {
    //
    // String m_path = Environment.getExternalStoragePublicDirectory(
    // Environment.DIRECTORY_PICTURES).getAbsolutePath();
    //
    // for (int i = 2; i <= 8; i++) {
    // for (int j = 1; j <= 4; j++) {
    // for (int z = 1; z <= 2; z++) {
    // for (int t = 1; t <= 6; t++) {
    // InputStream is = getAssets().open("file.mp3");
    // File fileoutput = new File(m_path, "W" + i + "D" + j + "P" + z + "_"
    // + t + ".mp3");
    //
    // Log.d("gen file ----> ", fileoutput.getAbsolutePath());
    // OutputStream out = new FileOutputStream(fileoutput);
    // copyFile(is, out);
    // }
    // }
    //
    // }
    // }
    //
    // } catch (Exception e) {
    //
    // }
    // }

    protected void generateDataAudio() {

    }

    protected void generateDataImage() {

    }

    protected void generateDataV2() {
        Thread createThread = new Thread(new Runnable() {

            @Override
            public void run() {
                DataProviderV2 dataProvider = new DataProviderV2(FlashScreenActivity.this);

                UrlModel urlModel = dataProvider.retrieveURLByURL("about:blank");

                SharedPreferences sharedpreferences = getSharedPreferences(
                        getString(R.string.user_data), Context.MODE_PRIVATE);

                Editor editor = sharedpreferences.edit();

                if (urlModel == null) {
                    long urlId = dataProvider
                            .insertUrlTable("https://uketuke.eiken.or.jp/tukyo/omotenashi/test/app/package.zip");
                    urlModel = dataProvider.retrieveURLByID(urlId);

                    editor.putLong(getString(R.string.user_data_connect_link), urlId);

                    // upzip data

                    // available..load data from package

                } else {
                    // available..load data from package

                    editor.putLong(getString(R.string.user_data_connect_link), urlModel.getId());

                }

                editor.commit();

                try {

                    InputStream inputStream = getAssets().open("lesson.json");
                    File outFileAudio = new File(urlModel.getDir(), "lesson.json");
                    FileOutputStream outputLessonJson = new FileOutputStream(outFileAudio);

                    copyFile(inputStream, outputLessonJson);

                    InputStream inputStream2 = getAssets().open("sentence.json");
                    File outFileSentences = new File(urlModel.getDir(), "sentence.json");
                    FileOutputStream outputSentencesJson = new FileOutputStream(outFileSentences);
                    copyFile(inputStream2, outputSentencesJson);

                    inputStream.close();
                    inputStream2.close();
                    outputLessonJson.close();
                    outputSentencesJson.close();

                } catch (Exception e) {

                }

                try {
                    FileInputStream stream = new FileInputStream(urlModel.getDir() + "/lesson.json");
                    FileChannel fc = stream.getChannel();
                    MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());

                    String jsonStr = Charset.defaultCharset().decode(bb).toString();
                    stream.close();

                    JSONArray jsonArr = new JSONArray(jsonStr);

                    for (int i = 0; i < jsonArr.length(); i++) {
                        JSONObject jobj = jsonArr.getJSONObject(i);

                        LessonModel model = new LessonModel();
                        model.setWeek(jobj.getInt("week"));
                        model.setDay(jobj.getInt("day"));
                        model.setLesson(jobj.getInt("lesson"));
                        model.setSubject(jobj.getString("subject"));
                        model.setDay_subject(jobj.getString("day_subject"));
                        model.setCover_image(jobj.getString("cover_image"));
                        model.setDone(jobj.getInt("done"));

                        dataProvider.insertLesson(model);
                        Log.d("json", jobj.toString());
                    }

                } catch (Exception e) {

                }

                try {
                    FileInputStream stream2 = new FileInputStream(urlModel.getDir()
                            + "/sentence.json");
                    FileChannel fc2 = stream2.getChannel();
                    MappedByteBuffer bb2 = fc2.map(FileChannel.MapMode.READ_ONLY, 0, fc2.size());

                    String jsonStr = Charset.defaultCharset().decode(bb2).toString();
                    stream2.close();
                    JSONArray jsonArr = new JSONArray(jsonStr);

                    for (int i = 0; i < jsonArr.length(); i++) {
                        JSONObject jobj = jsonArr.getJSONObject(i);

                        SentencesModel model = new SentencesModel();

                        model.setWeek(jobj.getInt("week"));
                        model.setDay(jobj.getInt("day"));
                        model.setLesson(jobj.getInt("lesson"));
                        model.setCharacter(jobj.getString("character"));
                        model.setQuestion_content(jobj.getString("question_content"));
                        model.setRecognize(jobj.getString("recognize"));
                        model.setAudio_name(jobj.getString("audio_name"));
                        model.setSentences(jobj.getInt("sentence"));

                        dataProvider.insertSentences(model);
                        Log.d("json", jobj.toString());
                    }

                } catch (Exception e) {
                    Log.e("install json", e.toString());
                }

                // insert audio file

                copyAudioFile(urlModel.getDir(), "audio");
                // insert image file
                copyImageFile(urlModel.getDir(), "image");

                Editor edit = reference.edit();
                edit.putBoolean(getString(R.string.user_data_about_blank), true);
                edit.commit();

            }

        });

        createThread.start();
    }

    private void copyFile(InputStream in, OutputStream out) throws IOException {

        byte[] buffer = new byte[1024];
        int read;

        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.flash_screen, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void copyAudioFile(String desfolder, String folder) {
        AssetManager assetManager = getAssets();
        String[] files = null;
        try {
            files = assetManager.list(folder);
        } catch (IOException e) {
            Log.e("tag", "Failed to get asset file list.", e);
        }
        for (String filename : files) {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = assetManager.open("audio/" + filename);

                File folderDes = new File(desfolder + "/audio/");
                if (!folderDes.exists()) {
                    folderDes.mkdirs();
                }

                File outFile = new File(folderDes.getAbsolutePath(), filename);
                // if (!outFile.exists()) {
                // outFile.mkdirs();
                // }

                Log.d("Copy file --->", filename);
                out = new FileOutputStream(outFile);
                copyFile(in, out);
            } catch (IOException e) {
                Log.e("tag", "Failed to copy asset file: " + filename, e);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // NOOP
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        // NOOP
                    }
                }
            }
        }
    }

    protected void copyImageFile(String dir, String folder) {
        AssetManager assetManager = getAssets();
        String[] files = null;
        try {
            files = assetManager.list(folder);
        } catch (IOException e) {
            Log.e("tag", "Failed to get asset file list.", e);
        }
        for (String filename : files) {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = assetManager.open("image/" + filename);

                File folderDes = new File(dir + "/image/");
                if (!folderDes.exists()) {
                    folderDes.mkdirs();
                }

                File outFile = new File(folderDes.getAbsolutePath(), filename);
                // if (!outFile.exists()) {
                // outFile.mkdirs();
                // }

                Log.d("Copy file --->", filename);
                out = new FileOutputStream(outFile);
                copyFile(in, out);
            } catch (IOException e) {
                Log.e("tag", "Failed to copy asset file: " + filename, e);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // NOOP
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        // NOOP
                    }
                }
            }
        }
    }

}
